package com.wang.example.netty.handler.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wang.basic.netty.handler.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

/**
 * 将ByteBuf数据 转为对象
 */
public class EchoServerInHandler1 extends ChannelInboundHandlerAdapter {
    /**
     * 服务端读取到网络数据后的处理
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        //ByteBuf为netty实现的缓冲区
        ByteBuf in = (ByteBuf)msg;
        String msgStr = in.toString(CharsetUtil.UTF_8);
        System.out.println("EchoServerInHandler1 处理:" + msgStr);
        Message message = JSON.parseObject(msgStr,new TypeReference<Message>(){});
        ReferenceCountUtil.release(msg);//通过使用 ReferenceCountUtil.realse(...)方法释放资源
        ctx.fireChannelRead(message);
    }

}
